package org.jeecg.modules.demo.crm.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.crm.dto.CProjectApplicationDTO;
import org.jeecg.modules.demo.crm.dto.CProjectApplicationSimpleDTO;
import org.jeecg.modules.demo.crm.entity.CProjectApplication;
import org.jeecg.modules.demo.crm.entity.CProjectApplicationSimple;
import org.jeecg.modules.demo.crm.mapper.CContractMapper;
import org.jeecg.modules.demo.crm.mapper.CProjectHeadQuotesMapper;
import org.jeecg.modules.demo.crm.mapper.CSubProjectMapper;
import org.jeecg.modules.demo.crm.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 项目信息
 * @Author: jeecg-boot
 * @Date:   2025-05-28
 * @Version: V1.0
 */
@Api(tags="项目信息")
@RestController
@RequestMapping("/crm/cProjectApplication")
@Slf4j
public class CProjectApplicationController extends JeecgController<CProjectApplication, ICProjectApplicationService> {
	@Autowired
	private ICProjectApplicationService cProjectApplicationService;

	 @Autowired
	 private ICProjectApplicationSimpleService cProjectApplicationSimpleService;

	@Autowired
	private CSubProjectMapper cSubProjectMapper;

	@Autowired
	private CProjectHeadQuotesMapper cProjectHeadQuotesMapper;

	@Autowired
	private CContractMapper cContractMapper;
	 @Autowired
	 private ICCommonService commonService;
	/**
	 * 分页列表查询
	 *
	 * @param cProjectApplication
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "项目信息-分页列表查询")
	@ApiOperation(value="项目信息-分页列表查询", notes="项目信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CProjectApplication>> queryPageList(CProjectApplication cProjectApplication,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        // 自定义查询规则
		QueryWrapper<CProjectApplication> queryWrapper = new QueryWrapper<>();

		if(StringUtils.isNotEmpty(cProjectApplication.getProjectNumber())){
			queryWrapper.like("project_number",cProjectApplication.getProjectNumber());
		}
		if(StringUtils.isNotEmpty(cProjectApplication.getLibraryId())){
			List<String> libraryIds = Arrays.stream(cProjectApplication.getLibraryId().split(","))
					.map(String::trim)
					.map(String::valueOf)
					.collect(Collectors.toList());
			queryWrapper.in("library_id",libraryIds);
		}
		if(StringUtils.isNotEmpty(cProjectApplication.getProjectName())){
			queryWrapper.like("project_name",cProjectApplication.getProjectName());
		}
		if(StringUtils.isNotEmpty(cProjectApplication.getProjectType())){
			queryWrapper.eq("project_type",cProjectApplication.getProjectType());
		}
		if(StringUtils.isNotEmpty(cProjectApplication.getProjectStatus())){
			queryWrapper.eq("project_status",cProjectApplication.getProjectStatus());
		}
		if(StringUtils.isNotEmpty(cProjectApplication.getContractingUnit())){
			queryWrapper.eq("contracting_unit",cProjectApplication.getContractingUnit());
		}
		if(StringUtils.isNotEmpty(cProjectApplication.getCompanyInfoId())){
			queryWrapper.eq("company_info_id",cProjectApplication.getCompanyInfoId());
		}
		if(StringUtils.isNotEmpty(cProjectApplication.getSource())){
			queryWrapper.eq("source",cProjectApplication.getSource());
		}
		queryWrapper.orderByDesc("is_favorite","establishment_time");

		Page<CProjectApplication> page = new Page<CProjectApplication>(pageNo, pageSize);
		IPage<CProjectApplication> pageList = cProjectApplicationService.page(page, queryWrapper);
		pageList.getRecords().stream().forEach(record -> {
			//查询分包次数
			Integer subcontrCount = cSubProjectMapper.subcontrCount(record.getId());
			record.setSubcontrCount(subcontrCount);
			//总项目报价记录
			BigDecimal totalProjectQuotation = cProjectHeadQuotesMapper.totalProjectQuotation(record.getId());
			record.setTotalProjectQuotation(totalProjectQuotation);

			//查询质保金 （合计）
			BigDecimal totalGuaranteeDeposit = cContractMapper.guaranteeDeposit(record.getId());
			record.setTotalGuaranteeDeposit(totalGuaranteeDeposit);
			// 质保金区间
			String warrantyPeriod = cContractMapper.warrantyPeriod(record.getId());
			record.setWarrantyPeriod(warrantyPeriod);

			//合同价格合计
			BigDecimal contractPrice = cContractMapper.contractPrice(record.getId());
			record.setContractPrice(contractPrice);
			String contractId = cContractMapper.contractByProjectId(record.getId());
			record.setContractId(contractId);
		});
		return Result.OK(pageList);
	}

	 @ApiOperation(value="项目信息-分页列表查询--普通", notes="项目信息-普通")
	 @GetMapping(value = "/listSimple")
	 public Result<IPage<CProjectApplicationSimple>> listSimple(CProjectApplication cProjectApplication,
																@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																HttpServletRequest req) {
		//查询分包商相关的项目
		 // 自定义查询规则
		 QueryWrapper<CProjectApplicationSimple> queryWrapper = new QueryWrapper<>();
		 if(commonService.permissionCheck()){
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 String projectId = cSubProjectMapper.projectPermissions(sysUser.getId());
			 if(projectId == null){
				 projectId = "-1";
			 }
			 List<Long> idList = Arrays.stream(projectId.split(","))
					 .map(String::trim)
					 .filter(StringUtils::isNotBlank)
					 .map(Long::valueOf)
					 .collect(Collectors.toList());
			 queryWrapper.in("id", idList);
		 }

		 if(StringUtils.isNotEmpty(cProjectApplication.getProjectNumber())){
			 queryWrapper.like("project_number",cProjectApplication.getProjectNumber());
		 }
		 if(StringUtils.isNotEmpty(cProjectApplication.getProjectName())){
			 queryWrapper.like("project_name",cProjectApplication.getProjectName());
		 }
		 if(StringUtils.isNotEmpty(cProjectApplication.getProjectType())){
			 queryWrapper.eq("project_type",cProjectApplication.getProjectType());
		 }
		 if(StringUtils.isNotEmpty(cProjectApplication.getProjectStatus())){
			 queryWrapper.eq("project_status",cProjectApplication.getProjectStatus());
		 }
		 if(StringUtils.isNotEmpty(cProjectApplication.getContractingUnit())){
			 queryWrapper.eq("contracting_unit",cProjectApplication.getContractingUnit());
		 }
		 if(StringUtils.isNotEmpty(cProjectApplication.getCompanyInfoId())){
			 queryWrapper.eq("company_info_id",cProjectApplication.getCompanyInfoId());
		 }
		 if(StringUtils.isNotEmpty(cProjectApplication.getSource())){
			 queryWrapper.eq("source",cProjectApplication.getSource());
		 }
		 queryWrapper.orderByDesc("is_favorite","establishment_time");



		 Page<CProjectApplicationSimple> page = new Page<CProjectApplicationSimple>(pageNo, pageSize);
		 IPage<CProjectApplicationSimple> pageList = cProjectApplicationSimpleService.page(page, queryWrapper);


		 pageList.getRecords().stream().forEach(record -> {
			/* //查询分包次数
			 Integer subcontrCount = cSubProjectMapper.subcontrCount(record.getId());
			 record.setSubcontrCount(subcontrCount);
			 //总项目报价记录
			 BigDecimal totalProjectQuotation = cProjectHeadQuotesMapper.totalProjectQuotation(record.getId());
			 record.setTotalProjectQuotation(totalProjectQuotation);

			 //查询质保金 （合计）
			 BigDecimal totalGuaranteeDeposit = cContractMapper.guaranteeDeposit(record.getId());
			 record.setTotalGuaranteeDeposit(totalGuaranteeDeposit);
			 // 质保金区间
			 String warrantyPeriod = cContractMapper.warrantyPeriod(record.getId());
			 record.setWarrantyPeriod(warrantyPeriod);

			 //合同价格合计
			 BigDecimal contractPrice = cContractMapper.contractPrice(record.getId());
			 record.setContractPrice(contractPrice);*/
		 });
		 return Result.OK(pageList);
	 }
	
	/**
	 *   添加
	 *
	 * @param cProjectApplication
	 * @return
	 */
	@AutoLog(value = "项目信息-添加")
	@ApiOperation(value="项目信息-添加", notes="项目信息-添加")
	@RequiresPermissions("crm:c_project_application:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CProjectApplication cProjectApplication) {
		cProjectApplicationService.installApplication(cProjectApplication);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param cProjectApplication
	 * @return
	 */
	@AutoLog(value = "项目信息-编辑")
	@ApiOperation(value="项目信息-编辑", notes="项目信息-编辑")
	@RequiresPermissions("crm:c_project_application:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CProjectApplication cProjectApplication) {
		cProjectApplicationService.updateApplication(cProjectApplication);
		return Result.OK("编辑成功!");
	}

	 @AutoLog(value = "项目信息-修改置顶功能")
	 @ApiOperation(value="项目信息-修改置顶功能", notes="项目信息-编辑")
	 @RequiresPermissions("crm:c_project_application:edit")
	 @RequestMapping(value = "/toggleFavorite", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> toggleFavorite(@RequestBody CProjectApplication cProjectApplication) {
		 cProjectApplicationService.toggleFavorite(cProjectApplication);
		 return Result.OK("编辑成功!");
	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目信息-通过id删除")
	@ApiOperation(value="项目信息-通过id删除", notes="项目信息-通过id删除")
	@RequiresPermissions("crm:c_project_application:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cProjectApplicationService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "项目信息-批量删除")
	@ApiOperation(value="项目信息-批量删除", notes="项目信息-批量删除")
	@RequiresPermissions("crm:c_project_application:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cProjectApplicationService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目信息-通过id查询")
	@ApiOperation(value="项目信息-通过id查询", notes="项目信息-通过id查询")
	@GetMapping(value = "/queryById")

	public Result<CProjectApplication> queryById(@RequestParam(name="id",required=true) String id) {
		CProjectApplication cProjectApplication = cProjectApplicationService.getById(id);
		if(cProjectApplication==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cProjectApplication);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cProjectApplication
    */
    @RequiresPermissions("crm:c_project_application:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CProjectApplication cProjectApplication) {
        return super.exportXls(request, cProjectApplication, CProjectApplication.class, "项目信息");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("crm:c_project_application:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CProjectApplication.class);
    }





	 @ApiOperation(value="登陆用户", notes="登陆用户")
	 @GetMapping(value = "/getLoginUser")
	 public Result<LoginUser> getLoginUser(){
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 return Result.OK(sysUser);
	 }

	 /**
	  * 项目信息-详情
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="项目信息-详情", notes="项目信息-详情")
	 @GetMapping(value = "/getOrderInfo")
	 @RequiresPermissions("crm:c_project_application:info")
	 public Result<CProjectApplicationDTO> getOrderInfo(@RequestParam(name="id",required=true) String id
	 ) {
		 //查询权限
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 CProjectApplicationDTO data= cProjectApplicationService.getOrderInfo(id,sysUser);
		 return Result.OK(data);
	 }

	 @ApiOperation(value="项目信息-详情", notes="项目信息-详情")
	 @GetMapping(value = "/getOrderInfoSimple")
	 public Result<CProjectApplicationSimpleDTO> getOrderInfoSimple(@RequestParam(name="id",required=true) String id) {
		 //查询权限
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 CProjectApplicationSimpleDTO data= cProjectApplicationSimpleService.getOrderInfo(id,sysUser);
		 return Result.OK(data);
	 }

}
